/*******************************config******************************/
var MasterConfig = function() {
    var t = {
            baseUrl: "",
            is_debug:false,
            baseMobileUrl: location.origin + "/",
            platName:"程序测试",
        },

        e = {};
    return e.C = function(e) {
        return t[e]
    },
        e
} ();
/*******************************config******************************/

function CustomWidget(){
    this.onready = [];
    this.readyStatus = false;
    this.ready = function(readyFunc){
        this.readyStatus?readyFunc():this.onready.push(readyFunc);
    };

    this.exec = function(){
        for(var i=0;i<this.onready.length;i++){
            this.onready[i]();
        }
        this.readyStatus=true;
    }
}

(function(){
    window.Login = new CustomWidget();
    window.xHeader = new CustomWidget();
    window.Menu = new CustomWidget();
    window.Pager = new CustomWidget();
    window.Lister = new CustomWidget();
    window.Panel = new CustomWidget();
    window.Search = new CustomWidget();
    window.HeaderUtil = new CustomWidget();
    window.VideoUtil = new CustomWidget();
    window.AudioUtil = new CustomWidget();
})();

Date.prototype.format = function(fmt){
    var o = {
        "M+" : this.getMonth()+1,
        "d+" : this.getDate(),
        "h+" : this.getHours(),
        "m+" : this.getMinutes(),
        "s+" : this.getSeconds(),
        "q+" : Math.floor((this.getMonth()+3)/3),
        "S"  : this.getMilliseconds()
    };
    if(/(y+)/.test(fmt))
        fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
    for(var k in o)
        if(new RegExp("("+ k +")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ?
                (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
    return fmt;
}
String.prototype.replaceAll  = function(s1,s2){
    return this.replace(new RegExp(s1,"gm"),s2);
}
var MyStore = {
    getCookie : function(e) {
        return document.cookie.length > 0 && (c_start = document.cookie.indexOf(e + "="), -1 != c_start) ? (c_start = c_start + e.length + 1, c_end = document.cookie.indexOf(";", c_start), -1 == c_end && (c_end = document.cookie.length), unescape(document.cookie.substring(c_start, c_end))) : ""
    },
    getByLS : function(e){
        return localStorage.getItem(e);
    },
    setByLS : function(e,o){
        localStorage.setItem(e,o);
    },
    getObjByLS:function(e) {
        var b = localStorage.getItem(e);
        if(!b||b=='undefined')return false;
        return JSON.parse(localStorage.getItem(e));
    },
    setObjByLS : function(e,o){
        if(o) {
            localStorage.setItem(e,JSON.stringify(o));
        }
    },
    clearLS : function (){
        localStorage.clear();
    },
    setCookie:function (e, o, n) {
        var t = e + "=" + o + "; ",
            i = "";
        null !== n && void 0 !== n && (i = "expires=" + new Date(1e3 * n) + "; "),
            document.cookie = t + i + "path=/"
    },
}
function getUrlParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    var r = window.location.search.substr(1).match(reg);  //匹配目标参数
    if (r != null) return unescape(r[2]); return null; //返回参数值
}
function _GET() {
    var e = location.search,
        o = {};
    if ("" === e || void 0 === e) return o;
    e = e.substr(1).split("&");
    for (var n in e) {
        var t = e[n].split("=");
        o[t[0]] = t[1]
    }
    return o.from && delete o.code,
        o
}
function removeParamFromUrl(e) {
    var o = _GET();
    for (var n in e) delete o[e[n]];
    return location.pathname + buildUrlParamString(o)
}
function buildUrlParamString(e){
    var o = "";
    for (var n in e) o += n + "=" + e[n] + "&";
    o = o.slice(0, o.length - 1);
    var t = "" === o || void 0 === o;
    return t ? "": "?" + o
}


var common={
    log: function() {
        for (var e = arguments.length,
                 o = 0; e > o; o++) console.log(arguments[o])
    },
    alert: function(e) {
        "" === MyStore.getCookie("DevDebug") ? console.log(e) : alert(e)
    },
}
var AJAXFlag = true;
var RPC = {
    getApi: function(e) {
        return MasterConfig.C("baseUrl") + "/" + e;
    },
    invokeApi: function(e, o, n, t, i, r) {
        if (common.alert("url: " + o), AJAXFlag) { (null === t || void 0 === t) && (t = function() {}),
        (null === i || void 0 === i) && (i = function() {}),
        (null === r || void 0 === r) && (r = function() {});
            var a = {
                url: RPC.getApi(o),
                type: e,
                xhrFields: {
                    withCredentials: !0
                },
                dataType: "json",
                beforeSend: t,
                success: function(e) {
                    common.alert("success data: " + JSON.stringify(e).substr(0, 200));
                    var result = RPC.dealWithAjaxData(o, e);
                    if(result == 1){
                        i(e)
                    } else if(result == 2) {
                        r(e)
                    }
                },
                error: function(e) {
                    if(e.status==502) {
                        widgetUtil.toast("新的服务正在发布，请稍后");
                    } else if(e.status==400) {
                        widgetUtil.toast("功能升级中，请刷新页面后重试");
                    } else {
                        widgetUtil.toast("网络异常",3000);
                    }
                    common.alert("error data: " + JSON.stringify(e));
                }
            };
            null !== n && void 0 !== n && (a.data = JSON.stringify(n), ("PUT" == e || "POST" == e) && (a.contentType = "application/json; charset=UTF-8")),
                $.ajax(a)
        }
    },
    dealWithAjaxData:function(e, o) {
        if (common.log(e, o), o.success) return 1;
        switch ("" + o.errorCode) {
            case "40001":
                Login.ready(function(){
                    Login.show();
                });
                return 3;
            default:
                break;
        }
        return 2;
    }
};

(function(){

    function $gvl(i) {
        return i ? i : "";
    }
    function createItem(item) {
        var tpl = ITEM_TEXT;
        if(item.type == 'textarea') {
            tpl = ITEM_TEXTAREA;
        } else if(item.type == 'number') {
            tpl = ITEM_NUMBER;
        } else if(item.type == 'image') {
            tpl = ITEM_LOGO;
            item.maxImage = item.maxImage?item.maxImage:9;
            tpl = tpl.replaceAll("#IMAGE_TARGET_ID#",item.imageTargetId);
            tpl = tpl.replaceAll("#IMAGE_MAX_COUNT#",item.maxImage);
            imgFields.push(item);
        } else if(item.type == 'files') {
            tpl = ITEM_FILES;
            item.maxImage = item.maxImage?item.maxImage:9;
            tpl = tpl.replaceAll("#IMAGE_TARGET_ID#",item.imageTargetId);
            tpl = tpl.replaceAll("#IMAGE_MAX_COUNT#",item.maxImage);
            fileFields.push(item);
        } else if(item.type == 'select') {
            tpl = ITEM_SELECT;
            var options = "";
            item.options.forEach(function(value,idx,arr){
                var one = ITEM_OPTION.replaceAll("#O_VALUE#",value.value).replaceAll("#O_TITLE#",value.title);
                options+=one;
            });
            tpl = tpl.replace("#OPTIONS#",options);
        } else if(item.type == 'checker') {
            tpl = ITEM_CHECKER;
        } else if(item.type == 'datetime'){
            tpl = ITEM_DATETIME;
            dateFields.push("#"+item.name)
        }
        if(item.required) {
            tpl = tpl.replace("#ITEM_REQ#",ITEM_REQ);
        } else {
            tpl = tpl.replace("#ITEM_REQ#","");
        }
        var lentips = "";
        if(item.tlen){
            lentips = ITEM_LENGTH.replaceAll('#NAME#',$gvl(item.name)).replaceAll('#LENGTH#',$gvl(item.tlen));
        }
        return tpl.replaceAll('#TITLE#',$gvl(item.title))
            .replaceAll('#LENGTH_TIPS#', lentips)
            .replaceAll('#NAME#',$gvl(item.name))
            .replaceAll('#PLACEHOLDER#',$gvl(item.placeholder))
            .replaceAll('#ONDELETE#',$gvl(item.onDelete))
            ;
    }
    function createBtn(item) {
        var tpl = BTN_CONFIRM;
        return tpl.replaceAll('#TITLE#',$gvl(item.title))
            .replaceAll('#BTN_FUNC#',$gvl(item.func))
            ;
    }
    function createForm(fId, config) {
        $iForm = $(fId);
        $iForm.addClass("release_box");
        $iForm.append("<div class='release_title'>"+config.title+"</div>");

        $iBody = $("<div class='release_body'></div>")
        $iForm.append($iBody);
        config.items.forEach(
            function(value, index, array) {
                $iBody.append(createItem(value));
            }
        )
        $iBtns = $("<div class='release_footer bth_fix'></div>");
        $iBody.append($iBtns);
        config.btns.forEach(
            function(value){
                $iBtns.append(createBtn(value));
            }
        )
        setTimeout(function(){
            dateFields.forEach(function(df){defDateInit(df)});
            imgFields.forEach(function(df){imageFieldInit(df)});
            fileFields.forEach(function(df){fileFieldInit(df)});
        },1000);

    }

    var BTN_CONFIRM = "<span class='ib release_footBtn release_btnConfrim' ms-click='#BTN_FUNC#'>#TITLE#</span>"

    var ITEM_REQ = "<span class='mastText'>*</span>";
    var ITEM_LENGTH = "<span class='release_inputNum'>{{#NAME#.length}}&nbsp;\/&nbsp;#LENGTH#</span>";

    var ITEM_NUMBER = "<div class='release_item'><div class='r_title'>#TITLE##ITEM_REQ#</div><div class='r_content'><input class='r_input' type='number' placeholder='#PLACEHOLDER#' ms-duplex-string='#NAME#'></div></div>";
    var ITEM_TEXT = "<div class='release_item'><div class='r_title'>#TITLE##ITEM_REQ#</div><div class='r_content'><input class='r_input' type='text' maxlength='#LENGTH#' placeholder='#PLACEHOLDER#' ms-duplex-string='#NAME#'>#LENGTH_TIPS#</div></div>";
    var ITEM_TEXTAREA = "<div class='release_item'><div class='r_title'>#TITLE##ITEM_REQ#</div><textarea class='r_textarea ' placeholder='#PLACEHOLDER#' ms-duplex-string='#NAME#' maxlength='#LENGTH#'></textarea>&nbsp;&nbsp;#LENGTH_TIPS#</div>";

    var ITEM_SELECT = "<div class='release_item'><div class='r_title'>#TITLE##ITEM_REQ#</div><div class='r_content'><select class='r_select' ms-duplex-value='#NAME#'>#OPTIONS#</select></div></div>";
    var ITEM_OPTION = "<option value='#O_VALUE#'>#O_TITLE#</option>";

    var ITEM_LOGO = "<div class='release_item'><div class='r_title'>#TITLE##ITEM_REQ#</div><div class='r_content'><div class='r_img_region' ms-visible='#NAME#.length>0'><div class='addPic fl' ms-repeat-img='#NAME#' ms-css-background-image='url(\"{{img}}\")'><img ms-click='#ONDELETE#($index)' class='closeCode' src='../static/images/deleteIcon1.png' alt=''></div></div><input class='addPicText' accept='image/*' type='file' multiple='true' name='' id='#IMAGE_TARGET_ID#'/><label  ms-visible='#NAME#.length<#IMAGE_MAX_COUNT#' for='#IMAGE_TARGET_ID#'>选择</label></div></div>";

    var ITEM_FILES = "<div class='release_item'><div class='r_title'>#TITLE##ITEM_REQ#</div><div class='r_content'><div class='r_img_region' ms-visible='#NAME#.length>0'><div ms-repeat-img='#NAME#' class='attachLine'><a ms-href='{{img.file}}' class='attachLink'>{{img.name}}</a><img ms-click='#ONDELETE#($index)' class='attachDel' src='../static/images/deleteIcon1.png' alt=''></div></div><input class='addPicText' accept='*/*' type='file' multiple='false' name='' id='#IMAGE_TARGET_ID#'/><label  ms-visible='#NAME#.length<#IMAGE_MAX_COUNT#' for='#IMAGE_TARGET_ID#'>选择</label></div></div>";

    var ITEM_CHECKER = "<div class='release_item'><div class='r_title'>#TITLE#</div><div class='r_content'>" +
        "<input type='checkbox' id='checkbox_#NAME#' class='r_checker' ms-duplex-checked='#NAME#' /><label for='checkbox_#NAME#'></label>" +
        "</div></div>";

    var ITEM_DATETIME = "<div class='release_item'><div class='r_title'>#TITLE##ITEM_REQ#</div><div class='r_content'>" +
        "<input class='release_input laydate-icon' type='text' name='#NAME#' id='#NAME#' readonly placeholder='#PLACEHOLDER#' ms-duplex-string='#NAME#'/></div>";

    window.FORMUtil = {
        createForm:createForm
    };
    var imgFields = [];
    var dateFields = [];
    var fileFields = [];
    function fileFieldInit(t){
        var fname = t.name;
        $("#"+t.imageTargetId).on("change",function(){
            var nf = $("#"+t.imageTargetId)[0].files[0];
            uploadModule.uploadFile(nf,function(images){
                o[fname].push({file:images,name:nf.name});
                widgetUtil.toast(nf.name+"上传成功",800);
            },new Date().format("yyyyMMddhhmmss")+"-"+nf.name.trim())
        })
    }
    function imageFieldInit(t){
        var fname = t.name;
        $("#"+t.imageTargetId).on("change",function(){
            uploadModule.uploadFiles($("#"+t.imageTargetId)[0].files,function(images){
                o[fname].pushArray(images)
            })
        })
    }
    var idate = {};
    function ml(){//这个方法不能带参数,所以只好这样了
        window.laydate(idate);
    }
    function defDateInit(dateSel){
        idate = {
            elem: dateSel,
            format: 'YYYY-MM-DD hh:mm',
            min: '2016-03-13 23:59',//laydate.now(), //设定最小日期为当前日期
            max: '2099-06-16 23:59', //最大日期
            istime: true,
            istoday: false
        }
        ml();
    }
})();
